

import pdfplumber
from PIL import Image
import os

# 读取PDF文件
def extract_pdf_content(pdf_path):
    content = ""
    images_folder = "pdf_images"  # 图片存放的文件夹
    os.makedirs(images_folder, exist_ok=True)  # 创建图片文件夹，如果不存在的话

    with pdfplumber.open(pdf_path) as pdf:
        for page_num, page in enumerate(pdf.pages):
            text = page.extract_text()
            content += f"# Page {page_num + 1}\n{text}\n\n"

            # 提取图片并保存
            index =0
            for img in page.images:
                img_data = img['stream'].get_data()

                img_file_path = os.path.join(images_folder, f"image_{page_num}_{index}.png")
                with open(img_file_path, "wb") as img_file:
                    img_file.write(img_data)

                # 在Markdown中插入图片引用
                content += f"![Image {page_num}_{index}]({os.path.relpath(img_file_path, os.path.dirname(markdown_output_path))})\n\n"
                index += 1

    return content

# 写入Markdown文件
def write_to_markdown(content, markdown_output_path):
    with open(markdown_output_path, "w", encoding="utf-8") as md_file:
        md_file.write(content)

# 示例使用
pdf_path = "xxxxxmgl.pdf"
markdown_output_path = "output.md"

content = extract_pdf_content(pdf_path)
write_to_markdown(content, markdown_output_path)